package com.example.myproject.druidandmybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/**
 * 如果没有start automybatis,那么mybatis，那些包需要自己引用，同时这些自定义的配置也需要自己引用；
 * 现在连接池和mybaits配置都重写了；
 * 因为mybatis-spring-boot-starter 这个jar包下，
 *
 * 包含了mybatis-spring-boot-autoconfigure 有这个项目，这个歌项目下游引用了有spring.factorys
 * 这个包含了很多依赖，所以我们不需要自己引入了依赖。只需要配置
 *
 *
 * org.mybatis.spring.boot.autoconfigure MybatisAutoConfiguration
 * mapperscan 是都要配置的，不管是没有start(这个时候所有依赖的Jar包需要自己引入，同时
 * datasrouce,mybatis这些配置也需要自己写了。
 * )
 *
 */
import javax.sql.DataSource;
//重写mybatis配置
@Configuration
@EnableTransactionManagement
@Import(value = {MyBatisMapperScannerConfig.class,DruidDataSourceConfiguration.class})
public class MybatisConfig implements TransactionManagementConfigurer {

    @Autowired
    private DataSource dataSource;

    private String typeAliasPackage = "com.xxx.xxx.mybati.model";

    /**
     * 如果有xml自己就来配置
     *创建sqlSessionFactoryBean 实例
     * 并且设置configtion 如驼峰命名.等等
     * 设置mapper 映射路径
     * 设置datasource数据源
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
/** 设置mybatis configuration 扫描路径 */
        //sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
/** 设置datasource */
        sqlSessionFactoryBean.setDataSource(dataSource);
        //  sqlSessionFactoryBean.setMapperLocations();
/** 设置typeAlias 包扫描路径 */
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/mapper/*.xml"));
        // sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
        return sqlSessionFactoryBean;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}